<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>自动化重命名</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js"></script>
    <style> 
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
        }

        h1, h2 {
            color: #333;
        }

        form {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        label {
            display: block;
            margin-bottom: 5px;
        }

        input[type="file"] {
            margin-bottom: 10px;
        }

        .selected-columns {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }

        .selected-columns span {
            background-color: #e0e0e0;
            padding: 5px 10px;
            margin-right: 5px;
            margin-bottom: 5px;
            border-radius: 5px;
            cursor: move;
        }

        .success-message {
            color: green;
            font-weight: bold;
        }

        .error-message {
            color: red;
            font-weight: bold;
        }

        #student-table {
            margin-top: 20px;
            border-collapse: collapse;
            width: 100%;
        }

        #student-table th, #student-table td {
            border: 1px solid #ddd;
            padding: 8px;
        }

        #student-table th {
            background-color: #f2f2f2;
        }

        input[type="submit"] {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        input[type="submit"]:hover {
            background-color: #45a049;
        }

        .horizontal-columns {
            display: flex;
            flex-wrap: wrap;
        }

        .horizontal-columns label {
            margin-right: 10px;
        }
        .horizontal-columns span {
            margin-right: 10px;
        }
    </style>
    <script>
        $(document).ready(function () {
            $('#excel_file').change(function () {
                var fileName = $(this).val().split('\\').pop();
                $('#excel-file-name').text(fileName);
                loadStudentTable();
                generateSelectBoxes();
            });

            function loadStudentTable() {
                var formData = new FormData();
                formData.append('excel_file', $('#excel_file')[0].files[0]);
                $.ajax({
                    url: '/get_table',
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        $('#student-table').html(data);
                    },
                    error: function (xhr, status, error) {
                        console.log('Error:', error);
                    }
                });
            }

            function generateSelectBoxes() {
                var formData = new FormData();
                formData.append('excel_file', $('#excel_file')[0].files[0]);
                $.ajax({
                    url: '/get_columns',
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        var columns = JSON.parse(data);
                        var selectBoxes = '';
                        for (var i = 0; i < columns.length; i++) {
                            selectBoxes += `<input type="checkbox" id="column_${i}" name="columns" value="${columns[i]}">&nbsp;&nbsp;`;
                            selectBoxes += `<label for="column_${i}">${columns[i]}:</label><br>`;
                            if (i < columns.length - 1) {
                                selectBoxes += '&nbsp;&nbsp;&nbsp;&nbsp;';
                            }
                        }
                        $('#select-boxes').html(selectBoxes);
                    },
                    error: function (xhr, status, error) {
                        console.log('Error:', error);
                    }
                });
            }

            let sortable;
            function initSortable() {
                sortable = new Sortable(document.getElementById('selected-columns'), {
                    animation: 150,
                    onEnd: function () {
                        updateSelectedColumnsAfterDrag();
                    }
                });
            }

            function updateSelectedColumnsAfterDrag() {
                var selectedColumns = [];
                $('#selected-columns span').each(function () {
                    selectedColumns.push($(this).text());
                });
                $('#selected-columns-order').val(selectedColumns.join(','));
                updateFormatHint(selectedColumns);
            }

            function updateFormatHint(selectedColumns) {
                var separator = $('#separator').val();
                var formatHint = '当前格式: ' + selectedColumns.join(separator);
                $('#format-hint').text(formatHint);
            }

            $(document).on('change', 'input[name="columns"]', function () {
                var selectedColumns = [];
                $('input[name="columns"]:checked').each(function () {
                    selectedColumns.push($(this).val());
                });
                var selectedColumnsDiv = $('#selected-columns');
                selectedColumnsDiv.empty();
                selectedColumns.forEach(function (column) {
                    selectedColumnsDiv.append(`<span>${column}</span>`);
                });
                $('#selected-columns-order').val(selectedColumns.join(','));
                initSortable();
                updateFormatHint(selectedColumns);
            });

            $('form').submit(function (e) {
                e.preventDefault();
                var formData = new FormData(this);
                formData.append('connector', $('#separator').val());  // 添加连接符到FormData中
                $.ajax({
                    url: '/upload',
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        $('#student-table').prepend('<p class="success-message">重命名成功！</p>');
                        loadStudentTable();
                        // 显示处理文件数量的弹窗
                        if (data.count !== undefined) {
                            alert('重命名完成! 请在本目录下的uploads目录中查看!');
                        } else {
                            alert('处理文件数量未知');
                        }
                    },
                    error: function (xhr, status, error) {
                        console.log('Response Text:', xhr.responseText);
                        $('#student-table').prepend('<p class="error-message">发生错误: ' + xhr.responseText + '</p>');
                    }
                });
            });

            $('#separator').on('input', function() {
                var selectedColumns = [];
                $('#selected-columns span').each(function () {
                    selectedColumns.push($(this).text());
                });
                updateFormatHint(selectedColumns);
            });

            $('#separator').on('blur', function () {
                var selectedColumns = [];
                $('#selected-columns span').each(function () {
                    selectedColumns.push($(this).text());
                });
                updateFormatHint(selectedColumns);
            });

            loadStudentTable();
        });
    </script>
</head>
<body>
    <h1>自动化重命名</h1>
    <form action="{{ url_for('upload') }}" method="post" enctype="multipart/form-data">
        <label for="folder">上传图片：</label>
        <input type="file" id="folder" name="folder" webkitdirectory directory multiple required><br><br>
       
        <label for="excel_file">Excel文件：</label>
        <input type="file" id="excel_file" name="excel_file" required><br><br>
        <div id="select-boxes" class="horizontal-columns">
            <!-- 动态生成的列复选框 -->
        </div>
       
        <div id="selected-columns" class="selected-columns">
            <!-- 动态显示选中的列名 -->
        </div>
        <p id="format-hint"></p>
        <label for="separator">连接符：</label>
        <input type="text" id="separator" name="separator" value="_"><br><br>
        <input type="hidden" id="selected-columns-order" name="selected_columns_order"><br><br>
        <input type="submit" value="开始重命名">
    </form>
    <h2><span id="excel-file-name"></span></h2>

    <div id="student-table"></div>
</body>
</html>